<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>绘制圆</title>
</head>

<body>
    <canvas width="500" height="500" id="oCanvas"></canvas>
    <script type="notjs" id="vertex">
        attribute vec2 a_position;
        attribute vec4 a_color;
        uniform vec2 screenSize;
        varying vec4 v_color;
        void main () {
            float x = a_position.x * 2.0 / screenSize.x  - 1.0;
            float y = 1.0 - (a_position.y * 2.0 / screenSize.y);
            gl_Position = vec4(x, y, 0, 1);
            v_color = a_color;
        }
    </script>
    <script type="notjs" id="fragment">
        precision mediump float;
        varying vec4 v_color;
        void main () {
            gl_FragColor = v_color;
        }
    </script>
    <script>
        var oCanvas = document.getElementById('oCanvas');
        var gl = oCanvas.getContext('webgl');
        if (!gl) {
            alert('浏览器不支持webgl');
        }

        // var str = ""
        // 创建着色器函数
        function createShader(gl, type, source) {
            var shader = gl.createShader(type);
            gl.shaderSource(shader, source);
            gl.compileShader(shader);
            var success = gl.getShaderParameter(shader, gl.COMPILE_STATUS);
            if (success) {
                return shader;
            }
            console.log(gl.getShaderInfoLog(shader));
        }

        var vetexStr = document.getElementById('vertex').innerText;
        var fragmentStr = document.getElementById('fragment').innerText;
        var vertexShader = createShader(gl, gl.VERTEX_SHADER, vetexStr);
        var fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentStr);

        function createProgram(gl, vertexShader, fragmentShader) {
            var program = gl.createProgram();
            gl.attachShader(program, vertexShader);
            gl.attachShader(program, fragmentShader);
            gl.linkProgram(program);
            var success = gl.getProgramParameter(program, gl.LINK_STATUS);
            if (success) {
                return program;
            }
            console.log(gl.getProgramInfoLog(shader));
        }
        var program = createProgram(gl, vertexShader, fragmentShader);
        console.log(program);
        gl.useProgram(program);


        var a_position = gl.getAttribLocation(program, "a_position");
        var pointsize = gl.getAttribLocation(program, "pointsize");
        var screenSize = gl.getUniformLocation(program, 'screenSize');
        var a_color = gl.getAttribLocation(program, "a_color");
        gl.uniform2f(screenSize, oCanvas.width, oCanvas.height);
        // gl.vertexAttrib4f(a_color, 1, 0, 0, 1);
        var positionBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
        var indexBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
        function draw() {
            var positionData = cirquePoints(100, 100, 100, 50, 50).positions;
            var indexData = cirquePoints(100, 100, 100, 50, 50).indices;
            // 绑定缓冲区数据  
            // 第一个参数绑定的缓冲区  
            //  第二个参数 传入的数据（要求时强类型语言需要你用类型化数组转换一下） 
            // 第三个参数是绘制的方式一般为gl.STATIC_DRAW 表示不会频繁改变缓冲区中的数据（webgl会根据这个参数做一些优化处理）
            gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(positionData), gl.STATIC_DRAW);
            gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indexData), gl.STATIC_DRAW);
            // 为变量分配数据  
            // 第一个参数是为哪个变量分配数据
            // 第二个参数是这个变量拥有数据的分量个数
            // 第三个参数是数据类型
            // 第四个参数是 如果是非浮点型数据是否将数据进行归一化  如果设置为true 数值类型字节大小在-128到127之间的数（BYTE）回转传承-1.0 到1.0之间，数值类型字节大小在0 到255之间的数（UNSIGNED_BYTE）变为0.0 到1.0之间，SHORT也是转换到-1.0 - 1.0之间，如果该值为false  则按照用户输入的数据处理。
            // 第四个参数说白了就是只有在第三个参数除了为FLOAT之外的（即为UNSIGNED_BYTE, SHORT, UNSIGNED_SHORT, INT, UNSIGNED_INT）时实用  
            // 第五个参数为两个顶点之间的字节数，也就是每个顶点的字节数，如果设置为0 则代表两个顶点之间字节数为 顶点数据分量 * 每个元素的字节数
            // 第六个参数为当前变量数据是从每个顶点数据的哪一位开始取
            gl.vertexAttribPointer(a_position, 2, gl.FLOAT, false, 4 * 5, 0);
            gl.vertexAttribPointer(a_color, 3, gl.FLOAT, false, 4 * 5, 4 * 2);
            // 启用这个位置数据
            gl.enableVertexAttribArray(a_position);
            gl.enableVertexAttribArray(a_color);
            // 绘制三角形
            gl.drawElements(gl.TRIANGLE_STRIP, indexData.length , gl.UNSIGNED_SHORT, 0);
            // gl.drawArrays(gl.TRIANGLE_FAN, 0, 52);
        }


        // function circlePoints(x, y, radius, n) {
        //     var points = [x, y, 1, 0, 0];
        //     for (var i = 0; i <= n; i ++) {
        //         var angle = i * Math.PI * 2 / n;
        //         pointx = radius * Math.cos(angle) + x;
        //         pointy = radius * Math.sin(angle) + y;
        //         points.push(pointx, pointy, Math.random(), Math.random(), Math.random());
        //     }

        //     return points;
        // }
        function cirquePoints(x, y, outerRadius, innerRadius, n) {
            var positions = [];
            var indices = [];
            var color = {
                r: 0,
                g: 0,
                b: 0,
            }
            for (var i = 0; i < n; i ++) {
                color = {
                    r: Math.random(),
                    g: Math.random(),
                    b: Math.random()
                };
                var angle = i * Math.PI * 2 / n;
                var innerX = x + innerRadius * Math.cos(angle);
                var innerY = y + innerRadius * Math.sin(angle);
                var outerX = x + outerRadius * Math.cos(angle);
                var outerY = y + outerRadius * Math.sin(angle);
                positions.push(innerX, innerY, color.r, color.g, color.b);
                positions.push(outerX, outerY, color.r, color.g, color.b);
            
                var v0 = i * 2;
                var v1 = v0 + 1;
                var v2 = v0 + 2;
                var v3 = v0 + 3;
                if (i == n - 1) {
                    v2 = 0;
                    v3 = 1;
                }
                indices.push(v0, v1, v2, v3);
            
            }

            return {
                positions,
                indices
            }


        }

        draw();


    </script>
</body>

</html>
